# -*- coding: utf-8 -*-
"""
@File:    config.py
@Author:  jk.dong
@Desc:    程序的配置项加载
"""
import yaml
import logging
from pathlib import Path


# 当前程序的绝对路径 Path().absolute().parent
BASE_PATH = Path().absolute()


def load_config(section: str | list[str], file_path=None):
    """
    动态加载配置区域，这样方便接收服务和发送服务只加载需要的配置项，也方便测试
    params:
        section: yaml配置文件的一级对象
        file_path: yaml配置文件路径
    return: 配置项容器对象，可以是字典或列表
    """
    if not file_path:
        file_path = BASE_PATH / 'config.yaml'
    with open(file_path, 'r', encoding='utf-8') as file:
        config_ = yaml.safe_load(file)

    # 递归函数，用于将字典中的所有键转换为小写，并将path相关配置项设为绝对路径
    def standardize_keys(d):
        if isinstance(d, dict):
            new_dict = {}
            for k, v in d.items():
                if k.endswith('path') and v:
                    if not Path(v).is_absolute():
                        v = BASE_PATH.joinpath(v)
                new_dict[k.lower()] = standardize_keys(v)
            # {k.lower(): standardize_keys(v) for k, v in d.items()}
            return new_dict
        elif isinstance(d, list):
            return [standardize_keys(item) for item in d]
        else:
            return d
    
    result = standardize_keys(config_)
    # 根据参数section来返回对应的配置项，参数section必须在包含在可选区域
    optional_sections = ['db-setting', 'run-setting', 'receive-setting', 'import-setting', 'send-setting']
    # 单个配置区域
    if isinstance(section, str):
        section_str = section.lower()
        if section_str in optional_sections:
            return result.get(section_str)
        elif section == 'all':
            return result
        else:
            logging.warning(f"当前section({section}) 不在{optional_sections}区域")
            return result
    # 多个配置区域
    elif isinstance(section, list):
        dict_ = {}
        for s in section:
            s_ = s.lower()
            if s_ in optional_sections:
                dict_[s] = result.get(s)
            else:
                logging.warning(f"当前section({s_}) 不在{optional_sections}区域\t继续获取下一个section")
                continue
        return dict_ if dict_ else result


# 加载并标准化配置文件
RUN_CONF = load_config(section=['db-setting', 'run-setting', 'import-setting'])

db1_type = int(RUN_CONF['db-setting'].get('db1_type'))
db1_address = RUN_CONF['db-setting'].get('db1_address')
db1_name = RUN_CONF['db-setting'].get('db1_name')
db1_port = int(RUN_CONF['db-setting'].get('db1_port'))
db1_username = RUN_CONF['db-setting'].get('db1_username')
db1_password = RUN_CONF['db-setting'].get('db1_password')
db1_schema = RUN_CONF['db-setting'].get('db1_schema')
db_case = RUN_CONF['db-setting'].get('db_case')


if db_case and int(db_case):
    table_attachment = 'ATTACHMENT'
    table_broker = 'BROKER'
    table_docgeneral = 'DOCGENERAL'
    table_docreport = 'DOCREPORT'
    table_doctype = 'DOCTYPE'
    table_stock = 'STOCK'
    table_entity = 'ENTITY'
    table_entityconfig = 'ENTITYCONFIG'
    table_km_customerinfo = 'KM_CUSTOMERINFO'
    table_km_docrecievelog = 'KM_DOCRECIEVELOG'
    table_km_rawmaillog = 'KM_RAWMAILLOG'
    table_km_recvsendinfo = 'KM_RECVSENDINFO'
    table_km_spam = 'KM_SPAM'
    table_km_brokermail = 'KM_BROKERMAIL'
else:
    table_attachment = 'attachment'
    table_broker = 'broker'
    table_docgeneral = 'docgeneral'
    table_docreport = 'docreport'
    table_doctype = 'doctype'
    table_stock = 'stock'
    table_entity = 'entity'
    table_entityconfig = 'entityconfig'
    table_km_customerinfo = 'km_customerinfo'
    table_km_docrecievelog = 'km_docrecievelog'
    table_km_rawmaillog = 'km_rawmaillog'
    table_km_recvsendinfo = 'km_recvsendinfo'
    table_km_spam = 'km_spam'
    table_km_brokermail = 'km_brokermail'

second_db = RUN_CONF['import-setting'].get('save_attachment_second')
db2_type = int(RUN_CONF['db-setting'].get('db2_type')) if second_db else 1
db2_address = RUN_CONF['db-setting'].get('db2_address') if second_db else "127.0.0.1"
db2_name = RUN_CONF['db-setting'].get('db2_name') if second_db else ""
db2_port = int(RUN_CONF['db-setting'].get('db2_port')) if second_db else 3306
db2_username = RUN_CONF['db-setting'].get('db2_username') if second_db else "root"
db2_password = RUN_CONF['db-setting'].get('db2_password') if second_db else ""
db2_schema = RUN_CONF['db-setting'].get('db2_schema') if second_db else ""

